package org.mspring.mlog.service.impl;

import net.sf.ehcache.Ehcache;

import org.mspring.mlog.service.RegionCacheService;
import org.mspring.platform.cache.service.CacheService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 
 * @author Gao Youbo
 * @since 2013年12月29日
 */
@Service
public class RegionCacheServiceImpl implements RegionCacheService {

    private static final Logger log = LoggerFactory.getLogger(RegionCacheServiceImpl.class);

    @Autowired
    private CacheService cacheService;

    @Override
    public boolean cacheExists(String cacheName) {
        // TODO Auto-generated method stub
        return cacheService.cacheExists(getCacheName(cacheName));
    }

    @Override
    public Ehcache getRegionCache(String cacheName) {
        // TODO Auto-generated method stub
        return cacheService.getCache(getCacheName(cacheName));
    }

    @Override
    public Ehcache addRegionCache(String cacheName) {
        // TODO Auto-generated method stub
        if (cacheExists(cacheName)) {
            return getRegionCache(cacheName);
        }
        return cacheService.addCache(getCacheName(cacheName), 10000);
    }

    @Override
    public void updateCacheValue(String cacheName, String key, Object value, long expiry) {
        // TODO Auto-generated method stub
        Ehcache cache = addRegionCache(cacheName);
        if (cache == null) {
            log.error("can't found cache, cacheName = {}", cacheName);
        }
        cacheService.updateCacheValue(cache, key, value, expiry);
    }

    private String getCacheName(String cacheName) {
        return REGION_CACHE_NAME_PRE.concat(cacheName);
    }

}
